#include "Stategameplay.h"

GameplayState::GameplayState(Artman *artman)
{
	m_animsolver=NULL;
	m_sector=NULL;
	m_player=NULL;
	m_scrotum=NULL;
	p_artman=artman;
	m_id=0;

}

GameplayState::~GameplayState()
{
	if (m_animsolver!=NULL)
	{
		delete m_animsolver;
	}
	if (m_sector!=NULL)
	{
		delete m_sector;
	}
	if (m_scrotum!=NULL)
	{
		delete m_scrotum;
	}
	if (m_player!=NULL)
	{
		delete m_player;
	}
}

bool GameplayState::Init()
{
	m_animsolver=AnimationSolver::Create();
	if (m_animsolver==NULL)
	{
		return false;
	}
	m_player=new Player(sf::Vector2f (100,100),p_artman,m_animsolver);
	m_scrotum=new Scrotum(p_artman);
	m_player->LinkScrotum(m_scrotum);
	m_sector=Sector::Create("maps/tilemap0.tmx",p_artman,m_animsolver,m_player);
	if (m_sector==NULL)
	{
		return false;
	}
	m_view.setSize(sf::Vector2f(1280,768));

	return true;
}

State *GameplayState::Create(Artman *artman)
{
	GameplayState *state=new GameplayState(artman);
	if (state->Init())
	{
		return state;
	}
	delete state;

	return NULL;
}

void GameplayState::Foldout()
{


}

void GameplayState::Foldup()
{


}

void GameplayState::Update(float dt)
{
	dt=dt/50.0f;
	m_sector->Update(dt);
	m_scrotum->Update(dt,sf::Vector2f(m_player->getPosition().x,m_player->getPosition().y+64));

}

void GameplayState::UpdateView(sf::RenderWindow &window)
{
		//control camera
	sf::Vector2f ppos=m_player->getPosition();

	if (ppos.x<640){ppos.x=640;} if (ppos.y<384){ppos.y=384;}
	sf::Vector2 <int> size=m_sector->getBounds();
	if (ppos.x+640>size.x){ppos.x=size.x-640;}
	if (ppos.y+384>size.y){ppos.y=size.y-384;}
	m_view.setCenter(ppos);
	m_sector->m_level.SetDrawingBounds(sf::Rect<float> (ppos.x-640,ppos.y-384,1280,768));
	window.setView(m_view);
	ppos.x-=640;
	ppos.y-=384;
	ppos.x*=0.25F; ppos.y*=0.25F;
	//ppos.y=ppos.y/size.y;
	m_sector->m_level.setParallax(ppos);

}

void GameplayState::Draw(sf::RenderWindow &window)
{
	UpdateView(window);
	m_sector->m_level.Draw(window);
	m_sector->Draw(window);
	m_scrotum->Draw(window);
}
